package com.artisan.service.wx.impl;

import com.artisan.common.enums.OrderStateEnum2;
import com.artisan.common.utils.TimeFormatUtil;
import com.artisan.dao.*;
import com.artisan.medium.wx.service.WxOrderService;
import com.artisan.model.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by szw on 2017/6/15.
 */
@Service("wxOrderService")
public class WxOrderServiceImpl implements WxOrderService{

	@Autowired
	private CustomerOrderinfoMapper customerOrderinfoMapper;

	@Autowired
	private CustomerMapper customerMapper;

	@Autowired
	private WorkerMapper workerMapper;

	@Autowired
	private BusinessMapper bussinessMapper;

	@Autowired
	private AddressMapper addressMapper;

	@Autowired
	private CustomerScoreMapper customerScoreMapper;

	@Autowired
	private AddressInfosMapper addressInfosMapper;

	@Autowired
	private AssessLableMapper assessLableMapper;

	/**
	 * 查询订单详情
	 * @param tranId
	 * @return
	 */
	@Override
	public Map<String, Object> qOrderDetail(Integer tranId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//用户订单信息
		CustomerOrderinfo orderinfo = customerOrderinfoMapper.selectByPrimaryKey(tranId);
		if (orderinfo == null) {
			return null;
		}
		resultMap.put("orderNo", orderinfo.getOrderNo());
		resultMap.put("money", orderinfo.getMoney());
		resultMap.put("reserviceTime", TimeFormatUtil.dateToStrNoSecond(orderinfo.getServiceTime()));
		resultMap.put("message", orderinfo.getMessage());
		if (orderinfo.getState() == OrderStateEnum2.CLOSE.getValue()) {
			resultMap.put("state", OrderStateEnum2.FINISHED.getcState());
			resultMap.put("stateValue", OrderStateEnum2.FINISHED.getValue());
		} else {
			resultMap.put("state", OrderStateEnum2.getByValue(String.valueOf(orderinfo.getState())).getcState());
			resultMap.put("stateValue", orderinfo.getState());
		}
		resultMap.put("createTime", TimeFormatUtil.dateToStrFull(orderinfo.getCrtTime()));

		//判断用户是否已评价
		boolean hasAssess = false;
		if (orderinfo.getState() == OrderStateEnum2.FINISHED.getValue() || orderinfo.getState() == OrderStateEnum2.CLOSE.getValue()) {
			CustomerScoreExample scoreExample = new CustomerScoreExample();
			CustomerScoreExample.Criteria scoreCriteria = scoreExample.createCriteria();
			scoreCriteria.andOrderNoEqualTo(orderinfo.getOrderNo());
			List<CustomerScore> scores = customerScoreMapper.selectByExample(scoreExample);
			if (scores != null && scores.size() > 0) {
				hasAssess = true;
			}
		}
		resultMap.put("hasAssess", hasAssess);

		boolean canCancel = true;
		if (orderinfo.getState() == OrderStateEnum2.ALREADY_ORDER.getValue()
				&& orderinfo.getServiceTime().before(new Date())) {
			canCancel = false;
		}
		resultMap.put("canCancel", canCancel);

		String businessIdStr = orderinfo.getBids();
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotBlank(businessIdStr)) {
			String[] businessIds = businessIdStr.split(",");
			for (String id : businessIds) {
				Business bussiness = bussinessMapper.selectByPrimaryKey(Integer.parseInt(id));
				if (bussiness != null) {
					if (StringUtils.isNotBlank(sb.toString())) {
						sb.append(",");
					}
					sb.append(bussiness.getbName());
				}
			}
		}
		resultMap.put("reserviceType", sb.toString());

		Integer addressId = orderinfo.getaId();
		Address add = null;
		if (addressId != null) {
			add = addressMapper.selectByPrimaryKey(addressId);
		} else {
			Integer uid = orderinfo.getUserId();
			AddressExample example = new AddressExample();
			AddressExample.Criteria criteria = example.createCriteria();
			criteria.andUIdEqualTo(uid).andDefaultAddressEqualTo(true);
			List<Address> adds = addressMapper.selectByExample(example);
			if (adds != null && adds.size() > 0) {
				add = adds.get(0);
			}
		}

		if (add != null) {
			StringBuffer addStr = new StringBuffer();
			//省id
			String proId = add.getProvinceId();
			//市ID
			String cityId = add.getCityId();
			//县或区ID
			String areaId = add.getAreaId();
			//镇或者街道ID
			String streetId = add.getStreetId();
			AddressInfos addressInfos = null;
			addressInfos = addressInfosMapper.selectByPrimaryKey(proId);
			addStr.append(addressInfos.getName());
			addressInfos = addressInfosMapper.selectByPrimaryKey(cityId);
			addStr.append(addressInfos.getName());
			addressInfos = addressInfosMapper.selectByPrimaryKey(areaId);
			addStr.append(addressInfos.getName());
			if (StringUtils.isNotBlank(streetId)) {
				addressInfos = addressInfosMapper.selectByPrimaryKey(streetId);
				addStr.append(addressInfos.getName());
			}
			addStr.append(add.getAddress());
			resultMap.put("address", add.getAname());
			resultMap.put("uname", add.getuName());
			resultMap.put("phone", add.getAphone());
		}

		//工人信息
		Integer wId = orderinfo.getwUid();
		Map<String, Object> workerMap = new HashMap<>();
		if (wId != null) {
			Worker worker = workerMapper.selectByPrimaryKey(wId);
			workerMap.put("id",worker.getId());
			workerMap.put("name", worker.getwName());
			workerMap.put("logoUrl", worker.getLogo());
			//workerMap.put("")
			CustomerOrderinfoExample orderinfoExample = new CustomerOrderinfoExample();
			CustomerOrderinfoExample.Criteria orderCriteria = orderinfoExample.createCriteria();
			orderCriteria.andWUidEqualTo(wId);
			int count = customerOrderinfoMapper.countByExample(orderinfoExample);
			workerMap.put("num", count);
			workerMap.put("phone", worker.getPhone());
			//工人评分
			CustomerScoreExample scoreExample = new CustomerScoreExample();
			CustomerScoreExample.Criteria scoreCriteria = scoreExample.createCriteria();
			scoreCriteria.andWIdEqualTo(wId);
			scoreExample.setOrderByClause("assess_time desc");
			scoreExample.setLimitStart(0);
			scoreExample.setPageSize(10);
			List<CustomerScore> scores = customerScoreMapper.selectByExample(scoreExample);
			if (scores != null && scores.size() > 0) {
				int score = 0;
				for (CustomerScore cs : scores) {
					score += cs.getStars();
				}
				workerMap.put("score", new DecimalFormat("#.0").format(score/scores.size()));
			} else {
				workerMap.put("score", 5.0);
			}
			if (scores == null || scores.size() == 0) {
				workerMap.put("score", 5);
			}
			resultMap.put("hasWorker", true);
		} else {
			workerMap.put("name", "小工匠运营部");
			workerMap.put("phone", "18888888888");
			resultMap.put("hasWorker", false);
		}
		resultMap.put("craftsman", workerMap);


		//用户信息
		/*Integer cId = orderinfo.getUserId();
		Customer customer = customerMapper.selectByPrimaryKey(cId);
		resultMap.put("uname", customer.getuName());
		resultMap.put("phone", customer.getPhone());*/
		return resultMap;
	}

	/**
	 * 取消订单，修改订单状态为待退款
	 * @param orderN0
	 */
	@Override
	public int cancelOrder(String orderN0) {
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderN0);
		List<CustomerOrderinfo> orderinfos = customerOrderinfoMapper.selectByExample(example);
		if (orderinfos != null && orderinfos.size() > 0) {
			CustomerOrderinfo orderinfo = orderinfos.get(0);
			/*if (orderinfo.getState() == OrderStateEnum.WAIT_PAY.getValue()) {
				orderinfo.setIsdelete(true);
				customerOrderinfoMapper.updateByPrimaryKeySelective(orderinfo);
				return 3;
			}*/
			Calendar calendar = Calendar.getInstance();
			//两小时后，如果师傅已接单且距离上门服务时间不到两小时则不能取消订单
			calendar.add(Calendar.HOUR_OF_DAY,2);
			if (orderinfo.getState() == OrderStateEnum2.ALREADY_ORDER.getValue()
					&& orderinfo.getServiceTime().before(calendar.getTime())) {
				return 2;
			}
			//师傅已接单或者用户已付款，则修改订单状态 为待退款
			if (orderinfo.getState() == OrderStateEnum2.ALREADY_ORDER.getValue()
					|| orderinfo.getState() == OrderStateEnum2.WAITING_ORDER.getValue()) {
				orderinfo.setState(OrderStateEnum2.IN_AUDIT.getValue());
				orderinfo.setUpdateTime(new Date());
			}
			return customerOrderinfoMapper.updateByPrimaryKeySelective(orderinfo);
		}
		return 0;
	}

	/**
	 * 上门前两小时内取消订单扣除部分上门费用
	 * @param orderNo
	 * @return
	 */
	@Override
	public int cancelOrderAndDeductMoney(String orderNo) {
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderNo);
		List<CustomerOrderinfo> orderinfos = customerOrderinfoMapper.selectByExample(example);
		if (orderinfos != null && orderinfos.size() > 0) {
			CustomerOrderinfo orderinfo = orderinfos.get(0);
			orderinfo.setState(OrderStateEnum2.IN_AUDIT.getValue());
			orderinfo.setUpdateTime(new Date());
			return customerOrderinfoMapper.updateByPrimaryKeySelective(orderinfo);
		}
		return 0;
	}

	/**
	 * 根据用户ID和订单状态查询订单列表
	 * @param openId
	 * @param type
	 * @return
	 */
	@Override
	public List<Map<String, Object>> qOrder(String openId, Integer type) {
		List<Map<String, Object>> result = new ArrayList<>();
		//根据openID查询用户信息
		CustomerExample customerExample = new CustomerExample();
		CustomerExample.Criteria customerCriteria = customerExample.createCriteria();
		customerCriteria.andOpenIdEqualTo(openId);
		List<Customer> customers = customerMapper.selectByExample(customerExample);
		if (customers != null && customers.size() > 0) {
			Integer userId = customers.get(0).getId();
			//根据用户ID和订单状态查询订单信息
			List<Integer> types = new ArrayList<>();
			/*if (type == 1) {//代付款
				types.add(OrderStateEnum2.WAITING_PAY.getValue());
			} else if (type == 2) {//已付款，包括已付款，服务已完成，师傅已接单，待退款，已结算
				types.add(OrderStateEnum.ALREADY_DISPATCH.getValue());
				types.add(OrderStateEnum.CLOSE.getValue());
				types.add(OrderStateEnum.FINISH.getValue());
				types.add(OrderStateEnum.WAIT_RETURN.getValue());
				types.add(OrderStateEnum.WRIT_DISPATCH.getValue());
			}*/
			CustomerOrderinfoExample orderinfoExample = new CustomerOrderinfoExample();
			CustomerOrderinfoExample.Criteria orderCriteria = orderinfoExample.createCriteria();
			orderCriteria.andUserIdEqualTo(userId).andStateIn(types);
			List<CustomerOrderinfo> orderinfos = customerOrderinfoMapper.selectByExample(orderinfoExample);
			if (orderinfos != null && orderinfos.size() > 0) {
				for (CustomerOrderinfo info : orderinfos) {
					String bId = info.getBids();
					String[] bIds = bId.split(",");
					StringBuffer sb = new StringBuffer();
					if (bIds != null && bIds.length > 0) {

						for (String id : bIds) {
							Business business = bussinessMapper.selectByPrimaryKey(Integer.parseInt(id));
							if (business != null) {
								if (StringUtils.isNotBlank(sb.toString())) {
									sb.append(",");
								}
								sb.append(business.getbName());
							}
						}
					}
					String state = null;
					if (info.getState() == OrderStateEnum2.CLOSE.getValue()) {
						state = OrderStateEnum2.FINISHED.getcState();
					} else {
						state = OrderStateEnum2.getByValue(info.getState().toString()).getcState();
					}
					Map<String, Object> map = new HashMap<>();
					map.put("orderNo", info.getOrderNo());
					map.put("bName", sb.toString());
					map.put("ReserviceTime", TimeFormatUtil.dateToStrNoSecond(info.getServiceTime()));
					map.put("state", state);
					map.put("payPrice", info.getMoney());
					result.add(map);
				}
			}
		}
		return result;
	}

	/**
	 *
	 * @param openId
	 * @return
	 */
	@Override
	public Map<String, List<Map<String, Object>>> qOrders(String openId) {

		Map<String, List<Map<String, Object>>> resultMap = new HashMap<>();
		//根据openID查询用户信息
		CustomerExample customerExample = new CustomerExample();
		CustomerExample.Criteria customerCriteria = customerExample.createCriteria();
		customerCriteria.andOpenIdEqualTo(openId);
		List<Customer> customers = customerMapper.selectByExample(customerExample);
		if (customers != null && customers.size() > 0) {
			Integer userId = customers.get(0).getId();
			//根据用户ID和订单状态查询订单信息

			CustomerOrderinfoExample orderinfoExample = new CustomerOrderinfoExample();
			CustomerOrderinfoExample.Criteria orderCriteria = orderinfoExample.createCriteria();
			orderCriteria.andUserIdEqualTo(userId)//.andStateIn(types)
			.andIsdeleteEqualTo(false);
			orderinfoExample.setOrderByClause("update_time desc");
			List<CustomerOrderinfo> orderinfos = customerOrderinfoMapper.selectByExample(orderinfoExample);

			if (orderinfos != null && orderinfos.size() > 0) {
				List<Map<String, Object>> noPay = new ArrayList<>();
				List<Map<String, Object>> payed = new ArrayList<>();
				for (CustomerOrderinfo info : orderinfos) {
					String bId = info.getBids();
					String[] bIds = bId.split(",");
					StringBuffer sb = new StringBuffer();
					if (bIds != null && bIds.length > 0) {

						for (String id : bIds) {
							Business business = bussinessMapper.selectByPrimaryKey(Integer.parseInt(id));
							if (business != null) {
								if (StringUtils.isNotBlank(sb.toString())) {
									sb.append(",");
								}
								sb.append(business.getbName());
							}
						}
					}
					//待付款订单
					if (info.getState() == OrderStateEnum2.WAITING_PAY.getValue()) {
						Map<String, Object> noPayMap = new HashMap<>();
						noPayMap.put("orderId", info.getId());
						noPayMap.put("orderNo", info.getOrderNo());
						noPayMap.put("bName", sb.toString());
						noPayMap.put("ReserviceTime", TimeFormatUtil.dateToStrNoSecond(info.getServiceTime()));
						noPayMap.put("state", OrderStateEnum2.getByValue(info.getState().toString()).getcState());
						noPayMap.put("payPrice", info.getMoney());
						//noPayMap.put("stateValue", info.getState());
						noPay.add(noPayMap);
					} else {

						String state = null;
						int stateValue = -1;
						if (info.getState() == OrderStateEnum2.CLOSE.getValue()) {
							state = OrderStateEnum2.FINISHED.getcState();
							stateValue = OrderStateEnum2.FINISHED.getValue();
						} else {
							state = OrderStateEnum2.getByValue(info.getState().toString()).getcState();
							stateValue = info.getState();
						}
						Map<String, Object> payedMap = new HashMap<>();
						payedMap.put("orderId", info.getId());
						payedMap.put("orderNo", info.getOrderNo());
						payedMap.put("bName", sb.toString());
						payedMap.put("ReserviceTime", TimeFormatUtil.dateToStrNoSecond(info.getServiceTime()));
						payedMap.put("state", state);
						payedMap.put("stateValue", stateValue);
						payedMap.put("payPrice", info.getMoney());
						payed.add(payedMap);
					}
					/*String state = null;
					if (info.getState() == OrderStateEnum.CLOSE.getValue()) {
						state = OrderStateEnum.FINISH.getMessage();
					} else {
						state = OrderStateEnum.getByValue(info.getState().toString()).getMessage();
					}
					Map<String, Object> map = new HashMap<>();
					map.put("orderNo", info.getOrderNo());
					map.put("bName", sb.toString());
					map.put("ReserviceTime", TimeFormatUtil.dateToStrNoSecond(info.getServiceTime()));
					map.put("state", state);
					map.put("payPrice", info.getMoney());
					result.add(map);*/
				}//endfor
				resultMap.put("payed", payed);
				resultMap.put("unPay", noPay);
			}
		}
		return resultMap;
	}

	/**
	 * 删除订单
	 * @param orderNo
	 */
	@Override
	public void deleteOrder(String orderNo) {
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderNo);

		List<CustomerOrderinfo> infos = customerOrderinfoMapper.selectByExample(example);
		if (infos != null && infos.size() > 0) {
			infos.get(0).setIsdelete(true);
			infos.get(0).setUpdateTime(new Date());
			customerOrderinfoMapper.updateByPrimaryKeySelective(infos.get(0));
		}
	}

	/**
	 * 取消未付款订单
	 * @param orderNo
	 * @return
	 */
	@Override
	public String cancelOrderUnpay(String orderNo) {
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderNo);
		List<CustomerOrderinfo> orders = customerOrderinfoMapper.selectByExample(example);
		if (orders != null && orders.size() > 0) {
			Integer userId = orders.get(0).getUserId();
			orders.get(0).setIsdelete(true);
			orders.get(0).setUpdateTime(new Date());
			int i = customerOrderinfoMapper.updateByPrimaryKeySelective(orders.get(0));
			if (i < 1) {
				return null;
			}

			Customer customer = customerMapper.selectByPrimaryKey(userId);
			if (customer != null) {
				return customer.getOpenId();
			}
		}
		return null;
	}

	/**
	 * 确认订单
	 * @param orderNo
	 * @return
	 */
	@Override
	public void confirmOrder(String orderNo) {
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderNo);
		List<CustomerOrderinfo> orders = customerOrderinfoMapper.selectByExample(example);
		//如果订单是待确认状态，则修改订单状态为已完成服务
		if (orders != null && orders.size() > 0) {
			/*if(orders.get(0).getState() == OrderStateEnum.WORKER_CONFIRM.getValue()) {
				orders.get(0).setState(OrderStateEnum.FINISH.getValue());
			} else if (orders.get(0).getState() == OrderStateEnum.ALREADY_DISPATCH.getValue()) {
				orders.get(0).setState(OrderStateEnum.CUSTOMER_CONFIRM.getValue());
			}*/
			orders.get(0).setState(OrderStateEnum2.FINISHED.getValue());
			orders.get(0).setUpdateTime(new Date());
			customerOrderinfoMapper.updateByPrimaryKeySelective(orders.get(0));
		}
	}

	/**
	 * 用户评价标签
	 * @return
	 */
	@Override
	public Map<String, Object> qAssessLables() {
		Map<String, Object> result = new HashMap<>();
		List<AssessLable> lables = assessLableMapper.selectByExample(null);
		if (lables != null && lables.size() > 0) {
			List<AssessLable> goodLables = new ArrayList<>();
			List<AssessLable> badLables = new ArrayList<>();
			for (AssessLable al : lables) {
				if (al.getType() == 0) {
					goodLables.add(al);
				} else if (al.getType() == 1) {
					badLables.add(al);
				}
			}
			result.put("good", goodLables);
			result.put("bad", badLables);
		}
		return result;
	}

	/**
	 * 通过订单编号查询用户信息
	 * @param orderNo
	 * @return
	 */
	@Override
	public Customer qCustomerByOrderNo(String orderNo) {
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderNo);
		List<CustomerOrderinfo> orders = customerOrderinfoMapper.selectByExample(example);
		if (orders != null && orders.size() > 0) {
			Integer userId = orders.get(0).getUserId();
			Customer customer = customerMapper.selectByPrimaryKey(userId);
			if (customer != null) {
				return customer;
			}
		}
		return null;
	}

	/**
	 * 提交用户评价
	 * @param stars
	 * @param orderNo
	 * @param lableIds
	 * @param message
	 */
	@Override
	public void assess(Integer stars, String orderNo, String lableIds, String message) {
		CustomerScoreExample example = new CustomerScoreExample();
		CustomerScoreExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderNo);
		List<CustomerScore> scores = customerScoreMapper.selectByExample(example);
		if (scores != null && scores.size() > 0) {
			return;
		}
		CustomerOrderinfoExample orderinfoExample = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria orderCriteria1 = orderinfoExample.createCriteria();
		orderCriteria1.andOrderNoEqualTo(orderNo);
		List<CustomerOrderinfo> orders = customerOrderinfoMapper.selectByExample(orderinfoExample);
		Integer workerId = null;
		if (orders != null && orders.size() > 0) {
			workerId = orders.get(0).getwUid();
		}

		CustomerScore score = new CustomerScore();
		score.setAssessTime(new Date());
		score.setLableIds(lableIds);
		score.setMessage(message);
		score.setOrderNo(orderNo);
		score.setStars(stars);
		score.setwId(workerId);
		customerScoreMapper.insertSelective(score);
	}
}
